﻿module VirtualCity.Main

open Casanova
open Casanova.Utilities
open Casanova.Core
open Casanova.Coroutines
open Casanova.Game
open Casanova.Input
open Casanova.Math
open Casanova.Drawing
open VirtualCity
open VirtualCity.Scripts
open VirtualCity.Initialization
open VirtualCity.World
open VirtualCity.CityDescription
open VirtualCity.City
open VirtualCity.Rendering
open VirtualCity.PlanDescription
open VirtualCity.Setup.Items
open VirtualCity.Setup.Buildings
open VirtualCity.Setup.Agents
open VirtualCity.Setup.InputScripts
open VirtualCity.Scripts.Bus

let start_game num_agents automated_selection (custom_ai:World->Script) (device,content,exit) =

  #if USE_ORIGINAL_WORLD
  let world = Initialize.NewWorld(device, content, 7, buildings_distribution_original, 20.0f<m>, automated_selection)
  #else
  let world = Initialize.NewWorld(device, content, 12, buildings_distribution, 20.0f<m>, automated_selection)
  #endif
  let agent_scripts = create_agents num_agents world

  let inline (!) x = immediate_lookup x

  let slowdown_in_progress = var false

  let main =
    co{ 
      do run_ai_script (custom_ai world)
      for a in agent_scripts do run_script a
      for bus in world.City.Buses do run_ai_script (do_rounds(bus,world.City))
    } .&&>
     (co{
        let ts = time_speed
        let t0 = DateTime.Now
        do! yield_
        let t1 = DateTime.Now
        let dt = (t1-t0).TotalSeconds
        if dt >= 0.1 then
          do slowdown_in_progress := true
          do time_speed <- 60.0f * 4.0f
          do! wait 600.0f<s>
          do slowdown_in_progress := false
          do time_speed <- ts
      } |> repeat_)

  time_speed <- 60.0f * 8.0f

  let input = input_scripts automated_selection slowdown_in_progress world exit

  in world,main,input

let run num_agents = 
  Casanova.Game.Game<VirtualCity.World.World>.Create(start_game num_agents true (fun _ -> yield_), 1280, 800).Run()
